#!/usr/bin/node --harmony_async_await

/*jshit esverions:6*/

const config = require('./config');
const ModbusManager = require('./modbus_manager');
const Monitor = require('./moniter.js');
const MqttClient = require('./mqtt_client');
const winston = require('winston');
const fs = require('fs');
const moment = require('moment');
const MsgClient = require('./msg_client');
const btoa = require('btoa');

const logDir = 'log';

// create the log diretory if it does not exist
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir)
}

const timeFormatFn = function () {
  return moment().format('YYYY-MM-DD,H:mm:ss')
}
const logFn = function (msg) {
  const message = `${msg.message}`;
  if (config.encryptLog) {
    return btoa(message);
  }
  return message;

}
const logger = new(winston.Logger)({
  transports: [
    new(winston.transports.Console)({
      colorize: true,
      timestamp: timeFormatFn
    }),
    new(require('winston-daily-rotate-file'))({
      filename: `${logDir}/${config.mqtt.enterpriseNo}${config.mqtt.serialNo}-`,
      datePattern: 'yyyy-MM-dd',
      prepend: false,
      json: false,
      timestamp: timeFormatFn,
      formatter: logFn,
    })
  ]
})

let msgClient = new MsgClient();
let monitor = new Monitor(logger, msgClient);
let modbus = new ModbusManager(config.modbus, logger, msgClient, monitor);
let mqtt = new MqttClient(config.mqtt, monitor);



let sidMap = new Map()
let startTrans = true
let enterpriseId = null

mqtt.on('eid', (data) => {
  logger.info(`received seteid: ${data}`)
  enterpriseId = data;
  mqtt.modifyDataTopic(enterpriseId);
})

mqtt.on('sid', (data) => {
  logger.info(`received setsid: ${data}`)
  let sidArr = data.split(',')
  if (Array.isArray(sidArr)) {
    for (let entry of sidArr) {
      let idPair = entry.split(':')
      sidMap.set(idPair[0], idPair[1])
    }
  }
})

mqtt.on('trans', () => {
  logger.info('received start transtramission')
  startTrans = true
})

modbus.on('data', (data) => {
  if (startTrans) {
    let samples = []
    // transfer local sensorId to server provided sensorId
    let msgArr = data.split(',')
    for (let item of msgArr) {
      let valPair = item.split(':')
      if (sidMap.has(valPair[0])) {
        valPair[0] = sidMap.get(valPair[0])
      }
      samples.push(valPair.join(':'))
    }
    let now = moment().format('YYYY-MM-DD H:mm:ss')
    const msg = `${now}, ${samples}`;
    mqtt.publish(msg, {
      qos: 1
    })
    if (msgClient) {
      msgClient.send(msg);
    }
    logger.info(msg)
  }
})


monitor.on('power', (status) => {
  const msg = status ? 'poweroff' : 'poweron';
  logger.info(msg);
  mqtt.notify(msg, {
    qos: 1
  });
});

monitor.on('lid', (status) => {
  const msg = status ? 'lidopened' : 'lidclosed';
  logger.info(msg);
  mqtt.notify(msg, {
    qos: 1
  });
});
